﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ideas2Realize.Data.Business.Interface;
using Ideas2Realize.Helpers;

namespace Ideas2Realize.Controllers
{

    [Authorize()]
    public class UserController : BaseController
    {

        public UserController()
        {
        }

        public XmlResult PhoneTypes()
        {
            IEnumerable<Ideas2Realize.Data.Models.PhoneType> data = UserRepository.GetPhoneTypes();

            return new XmlResult(data.ToList());
        }

        //
        // GET: /User/
       
        public XmlResult List(int limit, int page)
        {
            PetaPoco.Page<Ideas2Realize.Data.Models.User> pagedObject = UserRepository.GetPaged(limit, page);

            return PagedResult<Ideas2Realize.Data.Models.User>(pagedObject);  
        }

        public XmlResult ListRoles()
        {
            var roles = UserRepository.GetRoles();

            return new XmlResult(roles);
        }

        [HttpPost()]
        public JsonResult Settings(FormCollection collection)
        {
            try
            {
                int? id = collection["Id"].ToNullableInt();
                int? roleId = collection["RoleId"].ToNullableInt();

                Ideas2Realize.Data.Models.User user;

                if (id.HasValue)
                    user = UserRepository.GetById(id.Value);
                else
                {
                    string username = collection["Username"];

                    if (string.IsNullOrEmpty(username))
                        throw new Exception("Username cannot be blank!");

                    if (UserRepository.GetByUsername(username) != null)
                        throw new Exception(string.Format("A user with {0} does already exists.", username)); 

                    user = new Data.Models.User();
                    user.Username = username;
                    user.Created = DateTime.Now;
                    user.CreatedBy = User.Identity.Name;
                }

                user.Address = collection["Address"];
                user.City = collection["City"];
                user.Email = collection["Email"];
                user.Firstname = collection["Firstname"];
                user.Lastname = collection["Lastname"];

                string newpass = collection["NewPassword"];
                string confirmpass = collection["PasswordConfirm"];

                // set new password
                if (!string.IsNullOrEmpty(newpass) || !string.IsNullOrEmpty(confirmpass))
                {
                    newpass = SecurityHelper.GetHash(newpass);
                    confirmpass = SecurityHelper.GetHash(confirmpass);

                    if (string.Equals(newpass, confirmpass, StringComparison.CurrentCulture))
                    {
                        user.Password = newpass;
                    }
                    else
                    {
                        throw new Exception("Passwords does not match.");
                    }
                }

                user.Phone1 = collection["Phone1"];
                user.Phone2 = collection["Phone2"];
                user.Phone3 = collection["Phone3"];
                user.Phone4 = collection["Phone4"];
                user.Phone5 = collection["Phone5"];
                user.PhoneType1 = collection["PhoneType1"].ToNullableInt();
                user.PhoneType2 = collection["PhoneType2"].ToNullableInt();
                user.PhoneType3 = collection["PhoneType3"].ToNullableInt();
                user.PhoneType4 = collection["PhoneType4"].ToNullableInt();
                user.PhoneType5 = collection["PhoneType5"].ToNullableInt();
                user.DepartmentId = collection["DepartmentId"].ToNullableInt();

                user.Title = collection["Title"];
                user.Zip = collection["Zip"];
                user.Changed = DateTime.Now;
                user.ChangedBy = User.Identity.Name;




                if (user.Id > 0)
                    UserRepository.Update(user, user.Id);
                else
                {
                    UserRepository.Insert(user);
                    UserRepository.AddToRole(user, roleId.Value); 
                }

                return Success(user);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }


        public JsonResult Settings(int? id)
        {
            Ideas2Realize.Data.Models.UsersView user = null;

            if (id.HasValue && id.Value > 0)
                user = UserRepository.GetViewById(id.Value); 
            else 
                user = UserRepository.GetViewByUsername(User.Identity.Name);

            // clear password, not need to send it with settings.
            user.Password = string.Empty;

            return Json(new
            {
                success = true,
                data = user
            }, JsonRequestBehavior.AllowGet);
        }

        public XmlResult DepartmentsList(int limit, int page)
        {
            PetaPoco.Page<Ideas2Realize.Data.Models.Department> pagedObject = UserRepository.GetPagedDepartments(limit, page);

            return PagedResult<Ideas2Realize.Data.Models.Department>(pagedObject);  
        }

        public XmlResult Departments()
        {
            return new XmlResult(UserRepository.GetDepartments());
        }

        [HttpPost()]
        public JsonResult SaveDepartment(FormCollection collection)
        {
            try
            {
                int? id = collection["Id"].ToNullableInt();
                int? responsibleId = collection["Responsible"].ToNullableInt();

                if (!responsibleId.HasValue)
                    throw new Exception("Need to set responsible for the department."); 

                Ideas2Realize.Data.Models.Department dep;

                if (id.HasValue)
                    dep = UserRepository.GetDepartmentById(id.Value);
                else
                    dep = new Data.Models.Department();

                dep.Name = collection["Name"];
                dep.Responsible = responsibleId.Value;

                UserRepository.SaveDepartment(dep);

                return Success(dep);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        public JsonResult GetDepartment(int? id)
        {
            Ideas2Realize.Data.Models.Department dept = null;

            if (id.HasValue && id.Value > 0)
                dept = UserRepository.GetDepartmentById(id.Value);

            return Json(new
            {
                success = true,
                data = dept
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
